<template>
  <n-card :bordered="false" class="proCard">
    <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
      <template #statusSlot="{ model, field }">
        <n-input v-model:value="model[field]" />
      </template>
    </BasicForm>

    <BasicTable
      :columns="columns"
      :request="loadDataTable"
      :row-key="(row) => row.id"
      ref="actionRef"
      :actionColumn="actionColumn"
      @update:checked-row-keys="onCheckedRow"
      :scroll-x="1090"
    >
      <template #tableTitle>
        <n-button type="primary" @click="addTable">
          <template #icon>
            <n-icon>
              <PlusOutlined />
            </n-icon>
          </template>
          新建
        </n-button>
      </template>

      <!-- <template #toolbar>
        <n-button type="primary" @click="reloadTable">刷新数据</n-button>
      </template> -->
    </BasicTable>

    <n-modal v-model:show="showModal" :show-icon="false" preset="dialog" title="新建">
      <n-form
        :model="formParams"
        :rules="rules"
        ref="formRef"
        label-placement="left"
        :label-width="80"
        class="py-4"
      >
        <n-form-item label="用户名" path="userName">
          <n-input placeholder="请输入用户名" v-model:value="formParams.userName" />
        </n-form-item>
        <n-form-item label="密码" path="userPwd">
          <n-input type="password" placeholder="请输入密码" v-model:value="formParams.userPwd" />
        </n-form-item>
        <n-form-item label="邮箱" path="email">
          <n-input placeholder="请输入用户名" v-model:value="formParams.email" />
        </n-form-item>
        <n-form-item label="备注" path="remark">
          <n-input type="textarea" placeholder="请输入备注" v-model:value="formParams.remark" />
        </n-form-item>
      </n-form>

      <template #action>
        <n-space>
          <n-button @click="() => (showModal = false)">取消</n-button>
          <n-button type="info" :loading="formBtnLoading" @click="confirmForm">确定</n-button>
        </n-space>
      </template>
    </n-modal>
  </n-card>
</template>

<script lang="ts" setup>
import { h, reactive, ref, unref } from 'vue';
import { useMessage, useDialog } from 'naive-ui';
import { BasicTable, TableAction } from '@/components/Table';
import { BasicForm, useForm } from '@/components/Form/index';
import { getList, addUser } from '@/api/system/user';
import { columns } from './columns';
import { PlusOutlined } from '@vicons/antd';
import { useRouter } from 'vue-router';
import { ResultEnum } from '@/enums/httpEnum';

const rules = {
  userName: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入用户名',
  },
  userPwd: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入密码',
  },
  email: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入邮箱',
  },
};

const schemas = [
  {
    field: 'userName',
    //   labelMessage: '这是一个提示',
    component: 'NInput',
    label: '用户名',
    componentProps: {
      placeholder: '请输入用户名',
      onInput: (e: any) => {
        console.log(e);
      },
    },
    //   rules: [{ required: true, message: '请输入用户名', trigger: ['blur'] }],
  },
  {
    field: 'email',
    component: 'NInput',
    label: '邮箱',
    componentProps: {
      placeholder: '请输入邮箱',
      showButton: false,
      onInput: (e: any) => {
        console.log(e);
      },
    },
  },
  {
    field: 'enable',
    component: 'NRadioGroup',
    label: '状态',
    componentProps: {
      options: [
        {
          label: '启用',
          value: 1,
        },
        {
          label: '停用',
          value: 0,
        },
      ],
      onUpdateChecked: (e: any) => {
        console.log(e);
      },
    },
  },
];

const router = useRouter();
const formRef: any = ref(null);
const message = useMessage();
const dialog = useDialog();
const actionRef = ref();

const showModal = ref(false);
const formBtnLoading = ref(false);
const formParams = reactive({
  userName: '',
  userPwd: '',
  email: '',
  remark: '',
});

const params = ref({
  pageSize: 5,
  name: 'xiaoMa',
});

const actionColumn = reactive({
  width: 220,
  title: '操作',
  key: 'action',
  fixed: 'right',
  render(record) {
    return h(TableAction as any, {
      style: 'button',
      actions: [
        // {
        //   label: '删除',
        //   icon: 'ic:outline-delete-outline',
        //   onClick: handleDelete.bind(null, record),
        //   // 根据业务控制是否显示 isShow 和 auth 是并且关系
        //   ifShow: () => {
        //     return true;
        //   },
        //   // 根据权限控制是否显示: 有权限，会显示，支持多个
        //   auth: ['basic_list'],
        // },
        {
          label: '编辑',
          onClick: handleEdit.bind(null, record),
          ifShow: () => {
            return true;
          },
          auth: ['basic_list'],
        },
      ],
      dropDownActions: [
        {
          label: '启用',
          key: 'enabled',
          // 根据业务控制是否显示: 非enable状态的不显示启用按钮
          ifShow: () => {
            return true;
          },
        },
        {
          label: '禁用',
          key: 'disabled',
          ifShow: () => {
            return true;
          },
        },
      ],
      select: (key) => {
        message.info(`您点击了，${key} 按钮`);
        handleEnable(record);
      },
    });
  },
});

const [register, {}] = useForm({
  gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
  labelWidth: 80,
  schemas,
});

function addTable() {
  showModal.value = true;

}

const loadDataTable = async (res) => {
  return await getList({ ...formParams, ...params.value, ...res });
};

function onCheckedRow(rowKeys) {
  console.log(rowKeys);
}

function reloadTable() {
  actionRef.value.reload();
}

function confirmForm(e) {
  e.preventDefault();
  formBtnLoading.value = true;
  formRef.value.validate(async (errors) => {
    if (!errors) {
      const response = await addUser(formParams);
      const { result, code } = response;
      if (code === ResultEnum.SUCCESS) {
        message.success('新建成功');
        setTimeout(() => {
          showModal.value = false;
          reloadTable();
        });
      }
    } else {
      message.error('请填写完整信息');
    }
    formBtnLoading.value = false;
  });
}

function handleEdit(record: Recordable) {
//   console.log('点击了编辑', record);
//   router.push({ name: 'basic-info', params: { id: record.id } });
  Object.assign(formParams, record);
  addTable();
}

function handleDelete(record: Recordable) {
  console.log('点击了删除', record);
  message.info('点击了删除');
}

function handleSubmit(values: Recordable) {
  console.log(values);
  reloadTable();
}

function handleReset(values: Recordable) {
//   formRef.value.restoreValidation();
//   const form: any = unref(formRef);
//   form.resetFields();
}
function handleEnable(record: Recordable) {
    dialog.info({
      title: '提示',
      content: '您想 ' + (record.enable ? '禁用':'启用') + ' 该用户么？',
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: () => {
        // delRole(record.id);
        reloadTable();
        message.success('提交成功');
      },
      onNegativeClick: () => {},
    });
}
</script>

<style lang="less" scoped></style>
